package app.project.streetlensproject.map;

import java.util.ArrayList;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import app.project.streetlensproject.HomeActivity;
import app.project.streetlensproject.ListPlaceActivity;
import app.project.streetlensproject.R;
import app.project.streetlensproject.adapter.ItemListPlaceAdapter;
import app.project.streetlensproject.compass3d.Compass3DActivity;
import app.project.streetlensproject.compass3d.CompassRenderer;
import app.project.streetlensproject.compass3d.GLSurfaceView;
import app.project.streetlensproject.model.Place;
import app.project.streetlensproject.serverapi.ServerAPI;
import app.project.streetlensproject.util.AsyncTask;
import app.project.streetlensproject.util.BundleKeys;
import app.project.streetlensproject.util.CommonUtils;
import app.project.streetlensproject.util.Constants;
import app.project.streetlensproject.util.DialogUtils;
import app.project.streetlensproject.util.GPSTracker;
import app.project.streetlensproject.util.GetDataTask;
import app.project.streetlensproject.util.IGetDataTask;
import app.project.streetlensproject.util.Utilities;

public class MapActivity extends Activity {

	private GoogleMap map;
	private GLSurfaceView mGLSurfaceView;
	// public static final LatLng HANOI = new LatLng(20.993776, 105.811417);
	// public static final LatLng HOGUOM = new LatLng(21.028667, 105.852148);
	// public static final LatLng SETA = new LatLng(21.030814, 105.78602);
	// public static final LatLng LUXEHOTEL = new LatLng(21.035961, 105.788355);
	public static final LatLng FPT = new LatLng(21.029151, 105.782222);
	// public static final LatLng PLACE = new LatLng(21.032897, 105.787436);

	/* put this into your activity class */
	private SensorManager mSensorManager;
	private float mAccel; // acceleration apart from gravity
	private float mAccelCurrent; // current acceleration including gravity
	private float mAccelLast; // last acceleration including gravity

	private LinearLayout layoutListView, layoutMapView1, layoutMapView2,
			layoutCameraRotate;
	//private RotateCameraSurface mViewCamera;
	private ListView listPlace;
	private ArrayList<Place> arrPlaces = new ArrayList<Place>();
	ArrayList<Place> placeInAngle = new ArrayList<Place>();
	private int categoryID = 0;
	private boolean isUserPlace;

	private ImageView mImageViewZoomPlace;
	private TextView mTextViewUser, mTextViewUser2;
	LatLng MYPLACE;

	ArrayList<Integer> startY;
	int startRow = 3;
	int rowHeight=40;
	
	@Override
	public void onCreate(Bundle circle) {
		super.onCreate(circle);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().setFormat(PixelFormat.RGBA_8888);
		
		setContentView(R.layout.activity_map);
		
		startY = new ArrayList<Integer>();
		for(int i=0;i<5;i++){
			startY.add(i);
		}
		categoryID = getIntent().getIntExtra(BundleKeys.CATE_ID,
				Constants.ID_C_ALL);
		isUserPlace = getIntent().getBooleanExtra(BundleKeys.IS_USER_PLACE,
				false);

		MYPLACE = new LatLng(HomeActivity.MY_LATITUDE,
				HomeActivity.MY_LONGITUDE);

		String nameUser = CommonUtils.getStringSetting(MapActivity.this,
				Constants.USER_NAME, "Guest");
		mTextViewUser = (TextView) findViewById(R.id.textViewUserName);
		mTextViewUser.setText(getResources().getString(R.string.name_hello) + nameUser);
		mTextViewUser.setOnClickListener(onClickUserName);

		/* do this in onCreate */
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mSensorManager.registerListener(mSensorListener,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);
		mAccel = 0.00f;
		mAccelCurrent = SensorManager.GRAVITY_EARTH;
		mAccelLast = SensorManager.GRAVITY_EARTH;

		GPSTracker gps;
		gps = new GPSTracker(MapActivity.this);
		// check if GPS enabled
		if (gps.canGetLocation()) {
			double latitude = gps.getLatitude();
			double longitude = gps.getLongitude();
			Log.e("Value", "Lat=" + latitude + "/Long=" + longitude);
		}

		// createListView();
		// createLayoutListView();
		createMapView1();
		createMapView2();

	}

	/**
	 * event when click user name
	 */
	private OnClickListener onClickUserName = new OnClickListener() {

		public void onClick(View arg0) {
			// display dialog option
			if (CommonUtils.getStringSetting(MapActivity.this,
					Constants.TOKEN_ID, null) != null) {
				DialogUtils.showDialogUser(MapActivity.this,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								if (which == 0) {// my place
									Intent i = new Intent(MapActivity.this,
											ListPlaceActivity.class);
									i.putExtra(BundleKeys.IS_USER_PLACE, true);
									startActivity(i);
								} else if (which == 1) {// change pass
									HomeActivity.TYPE_HOME = HomeActivity.TYPE_CHANGEPASS;
									finish();
								} else {// logout
									// isLogin = false;
									CommonUtils.saveStringSetting(
											MapActivity.this,
											Constants.TOKEN_ID, null);
									mTextViewUser
											.setText(getString(R.string.hello)
													+ " Guest");
									CommonUtils.saveStringSetting(
											MapActivity.this,
											Constants.TOKEN_ID, null);
									Toast.makeText(getApplicationContext(),
											R.string.logout_sucess,
											Toast.LENGTH_LONG).show();
								}
							}
						});

			} else {
				HomeActivity.TYPE_HOME = HomeActivity.TYPE_LOGIN;
				finish();
			}
		}
	};

	// // TODO Quan implement
	// public void gotoEditUser() {
	// //isCategoryFg = false;
	// Fragment fg = new FgEditUser();
	// getSupportFragmentManager().beginTransaction().replace(R.id.content_layout,
	// fg).commit();
	// }

	private void createLayoutListView() {
		layoutListView = (LinearLayout) findViewById(R.id.layoutListView);
		listPlace = (ListView) findViewById(R.id.listViewPlaces);

		final ArrayList<Place> arrP = new ArrayList<Place>();
		for (int i = 0; i < 10; i++) {
			Place pl = new Place();
			pl.placename = "Name" + i;
			pl.description = "Description" + i;
			pl.locationx = 21.028667f;
			pl.locationy = 105.852148f;
			arrP.add(pl);
		}
		listPlace.setAdapter(new ItemListPlaceAdapter(MapActivity.this, arrP,
				45));
		listPlace.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				// DialogUtils.showPlaceMenuContext(MapActivity.this,
				// arrP.get(position));
			}
		});
	}

	/**
	 * create mapview when device display portrait
	 */
	private void createMapView2() {
		layoutMapView2 = (LinearLayout) findViewById(R.id.layoutMapView2);
		//layoutCameraRotate = (LinearLayout) findViewById(R.id.layoutCameraRotate);
		//mTextViewUser2 = (TextView) findViewById(R.id.textViewUserName2);
	}

	/**
	 * create mapview when device parallel of land
	 */
	@SuppressLint("NewApi")
	private void createMapView1() {

		mImageViewZoomPlace = (ImageView) findViewById(R.id.imageViewZoomMyPlace);
		layoutMapView1 = (LinearLayout) findViewById(R.id.layoutMapView1);

		map = ((MapFragment) getFragmentManager().findFragmentById(
				R.id.mapFragment)).getMap();
		map.moveCamera(CameraUpdateFactory.newLatLngZoom(MYPLACE, 20));

		MarkerOptions mkOptionUser = new MarkerOptions();
		mkOptionUser.position(MYPLACE);
		mkOptionUser.title("It's me");
		mkOptionUser.snippet("@@@");
		mkOptionUser.icon(BitmapDescriptorFactory
				.fromResource(R.drawable.ic_user));

		map.addMarker(mkOptionUser);

		Utilities.getInstance()
				.drawCircle(
						map,
						MYPLACE.latitude,
						MYPLACE.longitude,
						CommonUtils.getIntSetting(MapActivity.this,
								Constants.RADIUS, 5) * 1000);

		// Zoom in, animating the camera.
		map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
		map.setOnInfoWindowClickListener(inforWindowClickListener);

		if (getIntent().getIntExtra(BundleKeys.PREV_PAGE,
				Constants.FROM_CATEGORY) == Constants.FROM_CATEGORY) {
			setDataFromCategory();
		} else {
			setDataFromListPlace();
		}

		mImageViewZoomPlace.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				map.moveCamera(CameraUpdateFactory.newLatLngZoom(MYPLACE, 20));
				// Zoom in, animating the camera.
				map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
			}
		});
	}

	/**
	 * set data if from list place activity
	 */
	private void setDataFromListPlace() {
		arrPlaces = ListPlaceActivity.listCurrentPlace;
		if (arrPlaces != null) {
			for (int i = 0; i < arrPlaces.size(); i++) {
				// Log.e("LatLong",
				// "Lat" + i + "=" + arrPlaces.get(i).locationx + "---" + "Long"
				// + i + "="
				// + arrPlaces.get(i).locationy);
				MarkerOptions mkOption = new MarkerOptions();
				mkOption.position(new LatLng(arrPlaces.get(i).locationx,
						arrPlaces.get(i).locationy));
				mkOption.title(arrPlaces.get(i).placename);
				mkOption.snippet(arrPlaces.get(i).description);
				mkOption.icon(Utilities.getInstance()
						.getBitmapDescriptionFromType(
								arrPlaces.get(i).categoryid));
				map.addMarker(mkOption);
			}
		}
	}

	/**
	 * set data if from category
	 */
	private void setDataFromCategory() {
		new GetDataTask(MapActivity.this, new IGetDataTask() {

			@Override
			public boolean doInBackGround() throws Exception {
				double locationX = HomeActivity.MY_LATITUDE;
				double locationY = HomeActivity.MY_LONGITUDE;
				arrPlaces = ServerAPI.GetNearbyPlace(categoryID, locationX,
						locationY, CommonUtils.getIntSetting(MapActivity.this,
								Constants.RADIUS, 5), 0, 100);
				return false;
			}

			@Override
			public void onPostExecute(boolean result) throws Exception {
				super.onPostExecute(result);

				if (arrPlaces == null) {
					Log.e("ArrPlace", "Null");
					arrPlaces = new ArrayList<Place>();

				} else {
					Log.e("ArrPlace", arrPlaces.size() + "");
					for (int i = 0; i < arrPlaces.size(); i++) {
						Log.e("LatLong", "Lat" + i + "="
								+ arrPlaces.get(i).locationx + "---" + "Long"
								+ i + "=" + arrPlaces.get(i).locationy);
						MarkerOptions mkOption = new MarkerOptions();
						mkOption.position(new LatLng(
								arrPlaces.get(i).locationx,
								arrPlaces.get(i).locationy));
						mkOption.title(arrPlaces.get(i).placename);
						mkOption.snippet(arrPlaces.get(i).description);
						mkOption.icon(Utilities.getInstance()
								.getBitmapDescriptionFromType(
										arrPlaces.get(i).categoryid));
						map.addMarker(mkOption);
					}

				}
			}

		}, false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	/**
	 * set data when rotate camera
	 */
	private void setDataCameraRotate(float angleRoll) {
		// check if from mapactivity or listview
		arrPlaces = ListPlaceActivity.listCurrentPlace;
		
		for(int i=0;i<arrPlaces.size();i++){
			arrPlaces.get(i).setCorner(angleRoll);
			if(IsSpaceAvailable(MapActivity.this,arrPlaces.get(i).updateAngleRotate())){
				placeInAngle.add(arrPlaces.get(i));
			}
		}
//		placeInAngle = Utilities.getInstance().getPlaceInAngle(this, arrPlaces,
//				angleRoll);
//
//		for (int i = 0; i < placeInAngle.size(); i++) {
//
//			Log.e("Angle item " + i, placeInAngle.get(i).updateAngleRotate()
//					+ "");
//		}
		
		//mViewCamera = new RotateCameraSurface(MapActivity.this, placeInAngle);
		//layoutCameraRotate.removeAllViews();
		//layoutCameraRotate.addView(mViewCamera);
		//layoutMapView2.setVisibility(View.VISIBLE);
	}

	// Event when click in window infor of maker
	OnInfoWindowClickListener inforWindowClickListener = new OnInfoWindowClickListener() {

		public void onInfoWindowClick(Marker maker) {
			// TODO Auto-generated method stub
			// Go to page detail of place
			String title = maker.getTitle();
			int position = Utilities.getInstance().getPositionMakerSelect(
					title, arrPlaces);
			Intent it = new Intent(MapActivity.this,
					PlaceDetailActivity.class);
			it.putExtra("place", arrPlaces.get(position));
			startActivity(it);
		}
	};

	private boolean isFinish = false;
	/**
	 * event sensor of device change
	 */
	private final SensorEventListener mSensorListener = new SensorEventListener() {
		// private boolean isFinish = false;

		public void onSensorChanged(SensorEvent se) {
			// Thang dung theo chieu doc thi y lon nhat
			// Thang dung theo chieu ngang thi x lon nhat
			// Nam mat song song voi mat dat thi z lon nhat
			float x = se.values[0];
			float y = se.values[1];
			float z = se.values[2];
			mAccelLast = mAccelCurrent;
			mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));
			float delta = mAccelCurrent - mAccelLast;
			mAccel = mAccel * 0.9f + delta; // perform low-cut filter

			if (x > y && x > z) {
				startActivity(new Intent(MapActivity.this,Compass3DActivity.class));
				layoutMapView1.setVisibility(View.GONE);
				layoutMapView2.setVisibility(View.VISIBLE);
				//mGLSurfaceView = new GLSurfaceView(MapActivity.this);
				//mGLSurfaceView.setRenderer(new CompassRenderer(MapActivity.this));
				//layoutMapView2.addView(mGLSurfaceView);
//				// get angle my place and fpt
////				float angle = 90F
////						+ Utilities.GetAngle(MYPLACE.latitude,
////								MYPLACE.longitude, FPT.latitude, FPT.longitude)
////						- Float.parseFloat(String.valueOf(y * (180F / Math.PI)));
////				mTextViewUser2.setText(String.valueOf(angle));
//				setDataCameraRotate(Float.parseFloat(String.valueOf(y*(180F/Math.PI))));
//				// Toast.makeText(getBaseContext(),
//				// "AngleRotate="+y/(Math.PI/180), Toast.LENGTH_SHORT).show();
//				// mTextViewUser2.setText(String.valueOf(y/(Math.PI/180F)));
//				// Log.e("Accell",mAccel+"");
//				// cho nay la quay theo truc x.. thay doi gia tri tren truc y,z
			}
			if (y > x && y > z) {
				//layoutCameraRotate.removeAllViews();
				layoutMapView1.setVisibility(View.GONE);
				layoutMapView2.setVisibility(View.GONE);
				layoutMapView2.removeAllViews();
				if (!isFinish) {
					Intent i = new Intent(MapActivity.this,
							ListPlaceActivity.class);
					i.putExtra(BundleKeys.IS_USER_PLACE, isUserPlace);
					i.putExtra(BundleKeys.CATE_ID, categoryID);
					startActivity(i);
					MapActivity.this.finish();
					isFinish = true;
				}

			}
			if (z > x && z > y) {
				layoutMapView1.setVisibility(View.VISIBLE);
				layoutMapView2.setVisibility(View.GONE);
				//layoutCameraRotate.removeAllViews();
			}

		}

		public void onAccuracyChanged(Sensor sensor, int accuracy) {
		}
	};

	@Override
	public void onConfigurationChanged(
			android.content.res.Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			if (!isFinish) {
				Intent i = new Intent(MapActivity.this, ListPlaceActivity.class);
				i.putExtra(BundleKeys.IS_USER_PLACE, isUserPlace);
				i.putExtra(BundleKeys.CATE_ID, categoryID);
				startActivity(i);
				MapActivity.this.finish();
				isFinish = true;
			}
		}
	}

	
	public boolean IsSpaceAvailable(Activity mActivity,
			float rotate) {
		Display localDisplay2 = mActivity.getWindowManager()
				.getDefaultDisplay();
		Point localPoint = new Point();
		localDisplay2.getSize(localPoint);
		int width = localPoint.x;
		//int height = localPoint.y;
		int mGapBetweenRects = 10;
		int bitmapWidth = 30;
		int rectWidth = 80;

		return (int) (4.0F * ((180.0F + rotate) / 360.0F * width)) >= ((Integer) startY
				.get(-1 + startY.size())).intValue()
				+ rectWidth
				+ bitmapWidth
				+ mGapBetweenRects;				
	}

	public void InsertItem(Activity mActivity, int paramInt, float rotate) {

		Display localDisplay2 = mActivity.getWindowManager()
				.getDefaultDisplay();
		Point localPoint = new Point();
		localDisplay2.getSize(localPoint);
		int width = localPoint.x;
//		int height = localPoint.y;
//		int mGapBetweenRects = 10;
		int i = (int) (4.0F * ((180.0F + rotate) / 360.0F * width));
		startY.add(Integer.valueOf(i));
		// rowInfo[paramInt].placeItem.add(paramStringList);
	}
	// Event when click maker in mapview

	@Override
	protected void onResume() {
		super.onResume();
		//mGLSurfaceView.onResume();
		mSensorManager.registerListener(mSensorListener,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	@Override
	protected void onPause() {
		mSensorManager.unregisterListener(mSensorListener);
		//mGLSurfaceView.onPause();
		super.onPause();
	}

	
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
}